package com.nit.store.service.Impl;

import com.alibaba.fastjson.JSON;
import com.nit.store.ex.ServiceException;
import com.nit.store.mapper.UserMapper;
import com.nit.store.pojo.dto.input.UserDto;
import com.nit.store.pojo.entity.UserEntity;
import com.nit.store.pojo.vo.UserInfo;
import com.nit.store.pojo.vo.UserInfoDetails;
import com.nit.store.pojo.vo.output.LoginOutput;
import com.nit.store.service.UserService;
import com.nit.store.util.GlobalPasswordEncoder;
import com.nit.store.util.JwtUtils;
import com.nit.store.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDetailsService userDeatilService;

    @Autowired
    private GlobalPasswordEncoder globalPasswordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @Value("${upload.askUrl}")
    private String askUrl;

    @Override
    public void register(UserDto userDto){
        String username=userDto.getUsername();
        if(userMapper.findByName(username)!=null)
        {
            log.warn("用户已存在",username);
            throw new ServiceException(JsonResult.State.ERR_CONFLICT,"用户已存在");
        }
        else{
            UserEntity userEntity = new UserEntity();
            String rowPassword = userDto.getPassword();
            String encodedPassword = globalPasswordEncoder.encode(rowPassword);
            userEntity.setUsername(username);
            userEntity.setPassword(encodedPassword);
            userEntity.setIsEnable(1);
            userEntity.setCreatedTime(LocalDateTime.now());
            userEntity.setCreatedUser(username);
            userEntity.setModifiedTime(LocalDateTime.now());
            userEntity.setModifiedUser(username);
            Integer row = userMapper.addUser(userEntity);
            if(row !=1)
            {
                log.warn("服务器忙，请稍后再次尝试！");
                throw new ServiceException(JsonResult.State.ERR_INTERNAL_ERROR,"服务器忙，请稍后再次尝试！");
            }
        }

    }

    @Override
    public LoginOutput login(UserDto userDto) {

        System.out.println(userDto.toString());

        UserInfoDetails userDetails = (UserInfoDetails) userDeatilService.loadUserByUsername(userDto.getUsername());

        if(userDetails==null)
        {
            throw new ServiceException(JsonResult.State.ERR_BAD_REQUEST,"用户名不存在!!");
        }
        if(!globalPasswordEncoder.matches(userDto.getPassword(),userDetails.getPassword())){
            throw new ServiceException(JsonResult.State.ERR_BAD_REQUEST,"密码错误!");
        }

        //测试
        System.out.println("登录获取的密码："+userDto.getPassword());
        System.out.println("数据库获取的密码："+userDetails.getPassword());
        System.out.println("userDetails返回的uid："+userDetails.getUid());
        System.out.println("userDetails返回的用户名："+userDetails.getUsername());
        System.out.println("userDetails返回的权限："+userDetails.getAuthorities());


        //讲权限信息转化为json格式 保存到jwt中
        Map<String,Object> claims = new HashMap<>();
        claims.put("uid",userDetails.getUid());
        claims.put("username",userDetails.getUsername());
        claims.put("permissions", JSON.toJSONString(userDetails.getAuthorities()));


        System.out.println(claims.toString());

        String token = jwtUtils.createToken(claims);
        LoginOutput loginOutput = new LoginOutput(userDetails.getUid(), userDetails.getUsername(),token,askUrl + userDetails.getAvatar());
        return loginOutput;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword, Long uid) {
        UserEntity userEntity = userMapper.getUserInfoByUid(uid);
//        System.out.println("数据库对应密码："+userEntity.getPassword());
//        System.out.println("原密码："+oldPassword);
        if(!globalPasswordEncoder.matches(oldPassword,userEntity.getPassword()))
        {
            throw new ServiceException(JsonResult.State.ERR_CONFLICT,"原密码不正确");
        }
        String np = globalPasswordEncoder.encode(newPassword);
        System.out.println("加密后的新密码"+np);
        userEntity.setPassword(np);
        String user = userEntity.getUsername();
        LocalDateTime time = LocalDateTime.now();
        userEntity.setModifiedUser(user);
        userEntity.setModifiedTime(time);
        Integer row = userMapper.updatePassword(np,uid);
        if(row !=1)
        {
            log.warn("服务器忙，请稍后再次尝试！");
            throw new ServiceException(JsonResult.State.ERR_INTERNAL_ERROR,"服务器忙，请稍后再次尝试！");
        }
    }

    @Override
    public UserEntity showUserInfo(Long uid) {
        UserEntity user = userMapper.getUserInfoByUid(uid);
        return user;
    }

    @Override
    public void updateUserInfo(UserInfo userInfo) {
        System.out.println(userInfo);
        System.out.println(userInfo.getGender());
        UserEntity user = new UserEntity();
        if(userInfo.getGender()=="on")
        {
            user.setGender(1);

        } else
        {
            user.setGender(0);
        }
        user.setPhone(userInfo.getPhone());
        user.setEmail(userInfo.getEmail());

        user.setUid(userInfo.getUid());
        Integer row = userMapper.updateUserInfo(user);
        if(row!=1)
        {
            log.warn("服务器忙，请稍后再次尝试！");
            throw new ServiceException(JsonResult.State.ERR_INTERNAL_ERROR,"服务器忙，请稍后再次尝试！");
        }

    }

    @Override
    public void updateAvatar(Long uid, String avatar) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUid(uid);
        userEntity.setAvatar(avatar);
        Integer row = userMapper.updateAvatar(userEntity);
        if (row != 1) {
            log.warn("服务器忙，请稍后再次尝试！");
            throw new ServiceException(JsonResult.State.ERR_INTERNAL_ERROR, "服务器忙，请稍后再次尝试！");
        }

    }
}
